package hu.ikti.oamadmin.beans.customer;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import hu.ikti.oamadmin.beans.BaseBean;
import hu.ikti.oamadmin.beans.utils.DateHelper;
import hu.ikti.oamadmin.types.entities.Address;
import hu.ikti.oamadmin.types.entities.Customer;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessage.Severity;

@Name("customerBean")
@Scope(ScopeType.SESSION)
public class CustomerBean extends BaseBean implements Serializable {

	private static final long serialVersionUID = 1L;
	
	@In(create = true)
	@Out
	private Customer customer;

	@In(required = false)
	@Out(required = false)
	private Address address;

	@In(create = true)
	private DateHelper dateHelper;

	@DataModel
	private List<Customer> customerList;

	@Factory("customerList")
	public void getCustomers() {
		List<?> results = entityManager.createQuery(
				"select customer from Customer customer").getResultList();
		if (results != null) {
			customerList = new ArrayList<Customer>();
			for (Object object : results) {
				customerList.add((Customer) object);
			}
		}
	}

	@Begin(pageflow = "editCustomer", join = true)
	public String newCustomer() {
		return "start";
	}

	@Begin(pageflow = "editCustomer", join = true)
	public String editCustomer() {
		try {
			customer = entityManager.find(Customer.class, customer.getId());
			address = customer.getAddress();

			if (address == null)
				address = new Address();

			return "editAddress";
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public String saveCustomer() {
		try {
			customer.setBirthDate(dateHelper.getDate());

			if (address.getCountry() != null) {
				customer.setAddress(address);
			}

			customer = entityManager.merge(customer);

			if (!customerList.contains(customer)) {
				customerList.add(customer);
			}

			FacesMessages.instance().add(Severity.INFO, "Saved: #0 #1",
					customer.getFirstName(), customer.getLastName());

			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			FacesMessages.instance().add(Severity.ERROR, "System error!");
			return null;
		}
	}

	public void cancel() {
		FacesMessages.instance().add(Severity.WARN, "Transaction canceled!");
	}

}
